<template>
  <el-dialog
    class="dialog"
    v-model="visible"
    v-if="load"
    :title="type === 'add' ? '新增' : '编辑'"
    width="936"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <template v-if="type === 'add'">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model.trim="searchForm.sku" placeholder="SKU" clearable />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model.trim="searchForm.custom_sku"
            placeholder="自定义SKU"
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="search">查询</el-button>
        </el-col>
      </el-row>
    </template>
    <div class="mt-5">
      <el-tabs
        v-model="activeName"
        type="card"
        :before-leave="beforeLeave"
        class="my-tab-pane"
      >
        <el-tab-pane
          v-for="(item, index) in goods_sku_gallery"
          :key="item.custom_tag"
          :label="item.custom_tag"
          :name="item.custom_tag"
          class="relative"
        >
          <template #label>
            <span>{{ item.custom_tag }}</span>
            <svg-icon
              class="ml-2 inline-block"
              icon-class="Edit"
              @click="editEdit(item, index)"
            ></svg-icon>
            <span
              v-if="item.language_id_text"
              class="font-[10px] absolute -left-[4px] -top-[4px] bg-[#FAAD14] text-[#fff] rounded-tl-[4px] rounded-br-[4px] h-[20px] leading-[20px] px-[5px] scale-75"
            >
              {{ item.language_id_text }}
            </span>
            <div
              class="absolute -right-[1px] -top-[1px]"
              @click.stop="removeTab(item.custom_tag)"
            >
              <img class="w-[18px] h-[18px]" src="@/assets/images/closable.png" />
            </div>
          </template>
          <div class="product-title">
            <template v-if="type == 'add'">
              SKU:{{ form.goods_sku?.sku }}｜产品名称:{{ form.sku_cn_title }}
            </template>
            <template v-else>
              SKU:{{ item.goods_sku?.sku }}｜产品名称:{{ item.sku_cn_title }}
            </template>
          </div>
          <Module
            v-model="goods_sku_gallery[index].contents"
            :currentIndex="index"
            :customTag="item.custom_tag"
            @copyImage="copyImage($event, index)"
          ></Module>
        </el-tab-pane>
        <el-tab-pane key="add" name="add" class="flex" v-if="type == 'add'">
          <template #label>
            <span class="flex items-centerc">
              <svg-icon icon-class="add" class="mt-3" />
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div class="footer-handle">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">保 存</el-button>
      </div>
    </template>
  </el-dialog>
  <SelectTag ref="selectTagRef" @add="confirmAddTag" @edit="confirmEditTag"></SelectTag>
</template>
<script setup name="AddImage">
import { querySkuList, galleryDetail, galleryCreate, galleryEdit } from "../../api";
import { reactive, toRefs } from "vue";
import Module from "./components/Module";
import { ElMessage, ElMessageBox } from "element-plus";
import { deepClone } from "@/utils/index";
import SelectTag from "@/components/Selects/SelectTag";

const emits = defineEmits(["query"]);
const activeName = ref("默认");
let options = reactive(inject("options"));

const data = reactive({
  goods_sku_gallery: [],
  visible: false,
  visiblePopover: false,
  loading: false,
  searchForm: {
    spu: "",
    sku: "",
    custom_sku: "",
  },
  type: "add",
  imageTypeText: [],
  custom_index: null,
  load: false,
  form: {},
});

const {
  goods_sku_gallery,
  visible,
  loading,
  searchForm,
  type,
  imageTypeText,
  custom_index,
  load,
  form,
} = toRefs(data);

provide("handleType", type);
// provide("formData", goods_sku_gallery);
provide("galleryList", goods_sku_gallery);

const open = async (id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  goods_sku_gallery.value = initForm();
  if (id) {
    type.value = "edit";
    try {
      const res = await galleryDetail({
        id,
      });
      const data = res.data;
      data.contents = matchAndAdd(goods_sku_gallery.value[0].contents, data.contents);
      goods_sku_gallery.value = [data];
      activeName.value = data.custom_tag;
    } catch (e) {
      throw Error(e);
    }
  } else {
    type.value = "add";
    activeName.value = goods_sku_gallery.value[0].custom_tag;
  }
  visible.value = true;
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].image_type === array2[j].image_type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

const initForm = () => {
  imageTypeText.value = options.value.imageTypeText.map((i) => {
    i.image_type_text = i.label;
    i.image_type = i.value;
    i.values = [];
    return i;
  });

  return [
    {
      sku_id: "",
      sku: "",
      spu_category: "",
      sku_cn_title: "",
      custom_tag: "默认",
      goods_sku: {},
      contents: deepClone(imageTypeText.value),
    },
  ];
};

const search = async () => {
  if (
    !searchForm.value.sku &&
    !searchForm.value.custom_sku &&
    !searchForm.value.sai_he_sku
  ) {
    ElMessage.error("请输入SKU、自定义SKU或者赛盒SKU");
    return;
  }
  try {
    const res = await querySkuList(searchForm.value);
    const list = res.data;
    if (list.length == 0) return;
    const index = goods_sku_gallery.value.findIndex(
      (i) => i.custom_tag == activeName.value
    );
    if (index == -1) return;
    const { id, sku, spu_category, sku_cn_title } = list[0];
    // goods_sku_gallery.value[index].sku_id = id;
    // goods_sku_gallery.value[index].sku = sku;
    // goods_sku_gallery.value[index].goods_sku.sku = sku;
    // goods_sku_gallery.value[index].spu_category = spu_category;
    // goods_sku_gallery.value[index].sku_cn_title = sku_cn_title;
    form.value = {
      sku_id: id,
      sku: sku,
      goods_sku: {
        sku,
      },
      spu_category: spu_category,
      sku_cn_title: sku_cn_title,
    };
  } catch (e) {
    throw Error(e);
  }
};

const selectTagRef = ref();
const addTab = () => {
  selectTagRef.value.open("add");
};

const editEdit = (item, index) => {
  custom_index.value = index;
  selectTagRef.value.open("edit", {
    custom_tag: item.custom_tag,
    language_code: item.language_code,
    language_id: item.language_id,
  });
};

const removeTab = (targetName) => {
  if (goods_sku_gallery.value.length <= 1 || type == "edit") {
    return ElMessage.error("至少保留一个标签");
  }
  const contents = goods_sku_gallery.value;
  contents.forEach((tab, index) => {
    if (tab.custom_tag == targetName) {
      goods_sku_gallery.value.splice(index, 1);
      activeName.value =
        goods_sku_gallery.value[goods_sku_gallery.value.length - 1].custom_tag;
    }
  });
};

const beforeLeave = (currentName) => {
  if (currentName == "add") {
    addTab();
    return false;
  }
};

// 新增编辑标签回调
const confirmAddTag = (data) => {
  data.custom_tag_list.forEach((item) => {
    goods_sku_gallery.value.push({
      custom_tag: item.custom_tag,
      language_code: item.language_code,
      language_id: item.language_id,
      language_id_text: item.language_id_text,
      spu_id: "",
      spu: "",
      spu_category: "",
      spu_cn_title: "",
      goods_sku: {},
      contents: deepClone(imageTypeText.value),
    });
  });
};

const confirmEditTag = (item) => {
  activeName.value = item.custom_tag;
  goods_sku_gallery.value[custom_index.value].custom_tag = item.custom_tag;
  goods_sku_gallery.value[custom_index.value].language_code = item.language_code;
  goods_sku_gallery.value[custom_index.value].language_id = item.language_id;
  goods_sku_gallery.value[custom_index.value].language_id_text = item.language_id_text;
};

// 复制
const copyImage = (item, index) => {
  const { imageTypeSource, imageType } = item;
  const currentTabContent = goods_sku_gallery.value[index].contents;
  const copyTargetContentIndex = currentTabContent.findIndex(
    (v) => v.image_type === imageTypeSource
  );
  const currentContentIndex = currentTabContent.findIndex(
    (v) => v.image_type === imageType
  );

  const { values } = currentTabContent[copyTargetContentIndex];
  const { image_source } = currentTabContent[currentContentIndex];
  const copyValuesObj = values.reduce((pre, cur) => {
    if (cur.image_source === image_source) {
      pre.push(cur);
    }
    return pre;
  }, []);
  if (!copyValuesObj.length) {
    console.warn("未匹配到橱窗图（图片来源）");
    return;
  }
  if (!currentTabContent[currentContentIndex].values)
    currentTabContent[currentContentIndex].values = [];
  currentTabContent[currentContentIndex].values.push(...copyValuesObj);
};

// 保存
const save = async () => {
  if (type.value === "add") {
    const gallery = goods_sku_gallery.value.map((i) => {
      return {
        ...i,
        ...form.value,
      };
    });
    try {
      const res = await galleryCreate({
        goods_sku_gallery: gallery,
      });
      ElMessage.success(res.message);
      close();
    } catch (e) {
      throw Error(e);
    }
  } else if (type.value === "edit") {
    try {
      let _index = 0;
      for (let item of goods_sku_gallery.value) {
        // 兜底设置 视频给默认尺寸
        const { contents } = item;
        if (!contents) return;
        let _index_c = 0;
        for (let itemc of contents) {
          const { values } = itemc;
          if (!values) return;
          let _index_d = 0;
          for (let itemd of values) {
            const ar =
              goods_sku_gallery.value[_index].contents[_index_c].values[_index_d];
            if (!ar.image_size && ar.image_type_text === "视频")
              ar.image_size = "800 * 800";
            _index_d++;
          }
          _index_c++;
        }
        _index++;
      }
      const res = await galleryEdit({
        goods_sku_gallery: goods_sku_gallery.value,
      });
      ElMessage.success(res.message);
      close();
    } catch (e) {
      throw Error(e);
    }
  }
};

const close = () => {
  goods_sku_gallery.value = initForm();
  form.value = {};
  searchForm.value = {
    spu: "",
    sku: "",
    custom_sku: "",
  };
  visible.value = false;
};
defineExpose({ open });
</script>
<style scoped lang="scss">
.dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #999 !important;
  }
}

.footer-handle {
  text-align: center;
}

:deep(.el-tabs__nav) {
  display: flex;
}

:deep(.el-card__body) {
  display: flex;
  flex-direction: column;
}

:deep(.el-card__header) {
  border-bottom: 1px solid var(--el-card-border-color);
}

.product-title {
  padding: 10px 8px;
  // border-left: 1px solid var(--base-small-bg-color);
  // border-right: 1px solid var(--base-small-bg-color);
}
</style>
